package com.da.lon.wang.xlg.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;

import com.da.lon.wang.xlg.util.MyBitmapFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class DBHelper {
    public static final String DBNAME = "ocoffee.db";
    public static final String TABLE_IMG = "image";
    public static final int VERSION = 2;
    private SQLiteDatabase db;
    private Context context;
    private MyDBHelper myDBHelper;

    public DBHelper(Context context) {
        this.context = context;
    }

    /**
     * 添加图片
     *
     * @param path 图片路径
     * @param img  图片对象
     * @return 是否添加成功
     */
    public boolean insert(String path, Bitmap img) {
        ContentValues values = new ContentValues();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        img.compress(Bitmap.CompressFormat.PNG, 100, stream);
        values.put("path", path);
        values.put("img", stream.toByteArray());
        if (query(path) == null) {
            db.insert(TABLE_IMG, null, values);
            return true;
        }

        return false;
    }

    /**
     * 获取图片
     *
     * @param path 图片路径
     * @return 图片对象
     */
    public Bitmap query(String path) {
        Bitmap img = null;
        if (path != null) {
            String sql = "select img from image where path = ?;";
            Cursor cursor = db.rawQuery(sql, new String[]{path});
            while (cursor.moveToNext()) {
                byte[] bt = cursor.getBlob(cursor.getColumnIndex("img"));
                img = MyBitmapFactory.createImageThumbnail(new ByteArrayInputStream(bt));
                break;
            }
            cursor.close();
        }
        return img;
    }

    /**
     * 删除图片
     *
     * @param path 图片路径
     * @return 是否删除
     */
    public boolean delete(String path) {
        if (path != null && db.delete(TABLE_IMG, "path = ?", new String[]{path}) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 打开数据库
     */
    public void openDatabase() {
        if (db == null) {
            myDBHelper = new MyDBHelper(context, DBNAME, VERSION);
            db = myDBHelper.getWritableDatabase();
        }
    }

    class MyDBHelper extends SQLiteOpenHelper {
        public MyDBHelper(Context context, String name, int version) {
            super(context, DBNAME, null, VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + TABLE_IMG + " (path varchar(100) PRIMARY KEY , img BLOB not null)");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_IMG);
            onCreate(db);
        }
    }


}
